﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

delegate void TikTak(int x);

namespace Itrp
{
    class SuperInterpolator
    {
        private double dInitPos, dEndPos, dTime;
        private System.Timers.Timer aTimer;
        private static double left, weight = 0.0;
        private int service = 0;
        private DateTime StartTime, Now;
        private TimeSpan TimeLeft;
       
        public event TikTak TT;

        public SuperInterpolator(double x, double y, double z)
        {
            dInitPos = x;
            dEndPos = y;
            dTime = z * 1000;
        }

        public void Start()
        {
            aTimer = new System.Timers.Timer(1);
            aTimer.Elapsed += new ElapsedEventHandler(OnElapsed);
     //       GC.KeepAlive(aTimer);
            StartTime = DateTime.Now;
            aTimer.Start();
        }

        private void OnElapsed(object sender, EventArgs e)
        {
            Now = DateTime.Now;
            TimeLeft = Now - StartTime;
            left = dTime - TimeLeft.TotalMilliseconds;
            if ((Convert.ToInt16(left)) <= 0) aTimer.Stop();
            service = Calculate();
            TT(service);
        }

        private int Calculate()
        {
         //   int Substract = Convert.ToInt16(TimeLeft.TotalMilliseconds / 100);
            weight = TimeLeft.TotalMilliseconds / dTime;
            if (weight > 1) weight = 1;
            return Convert.ToInt16((dInitPos + (dEndPos - dInitPos) * weight));
            
        }

    }

    class Program
    {
        public static void Output(int x)
        {
            Console.WriteLine("Next value is " + Convert.ToString(x));
        }
        
        static void Main(string[] args)
        {
            Console.WriteLine("Enter start position: ");
            double x = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Enter end position: ");
            double y = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Enter time interval: ");
            double z = Convert.ToDouble(Console.ReadLine());

            SuperInterpolator strtr = new SuperInterpolator(x, y, z);
            Console.WriteLine("First value is: " + Convert.ToString(Convert.ToInt16(x)));
            strtr.TT += new TikTak(Output);

            strtr.Start();
            Console.ReadLine();
        }

        
    }

}
